package com.enlorenz.core.engine.imp.quartz;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.enlorenz.common.util.IdGenerator;
import com.enlorenz.core.engine.AbstractEngine;
import com.enlorenz.core.engine.IBuzHandler;

/**
 * Quartz执行者
 * @author Karma
 */
public class QuartzEngine extends AbstractEngine{
	//业务处理类
	protected IBuzHandler buzHandler;
	private Scheduler scheduler;
	//cron定时表达式
	private String cronExpression;
	//触发器
	private CronTrigger cronTrigger;
	private JobDetail jobDetail;
	//立即执行一次
	private Boolean immeStart=false;
	private String jobName;
	private String groupName;
	public void setBuzHandler(IBuzHandler buzHandler) {
		this.buzHandler = buzHandler;
	}
	
	/**
	 * 初始化
	 */
	public void initEngine() throws Exception {
		jobName="JOB_"+IdGenerator.getId();
		groupName="QuartzEngineJobGroup";
		
		// Initiate a Schedule Factory
		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
		// Retrieve a scheduler from schedule factory
		scheduler = schedulerFactory.getScheduler();
		// Initiate JobDetail with job name, job group, and executable job class
		jobDetail = new JobDetail(jobName,
				groupName, ElzQuartzJob.class);
		jobDetail.getJobDataMap().put(ElzQuartzJob.BUZ_HANDLER_KEY, buzHandler);
		// Initiate CronTrigger with its name and group name
		cronTrigger = new CronTrigger("EngineCronTrigger","QuartzEngineTriggerGroup");
		cronTrigger.setCronExpression(cronExpression);
	}
	

	@Override
	public boolean isAlive() {
		try {
			return scheduler.isStarted();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return false;
	}


	@Override
	public void shutdownEngine() throws Exception{
		scheduler.shutdown();
	}

	@Override
	public void startEngine() throws Exception{
		scheduler.start();
		scheduler.scheduleJob(jobDetail, cronTrigger);
		if(immeStart){
			this.scheduler.triggerJob(jobName, groupName);
		}
	}
	
	/**
	 * 设置cron表达式
	 * @param cronExpression cron表达式
	 */
	public void setCronExpression(String cronExpression) {
		this.cronExpression = cronExpression;
	}



	public void setImmeStart(Boolean immeStart) {
		this.immeStart = immeStart;
	}


	public Boolean getImmeStart() {
		return immeStart;
	}
	
	
}



